package poly4;
/*
    多态的使用场景:
        1. 拿父引用作为方法的形参,启动方法的方式有n+1种
            n : 此父类有多少种子类 1 : 父类自己
        2. 拿父类型作为方法的返回值类型,返回方法结果时可以有n+1种对象类型返回
        3. 拿父类型作为容器的数据类型,容器中的数据类型就可以是n+1种
            Object[] objs = new Object[10];
            ArrayList<Object> list = new ArrayList<Object>();
 */
public class Demo {
    public static void main(String[] args) {
        Shark shark = new Shark();//具体的刀头
        Dog dog = new Dog();
        Cat cat = new Cat();

        //启动useAnimal方法
        useAnimal(shark);
        useAnimal(dog);
        useAnimal(cat);

        System.out.println(shark);
        System.out.println(dog);
        System.out.println(cat);
    }
    /*
        第一次调用方法 : Animal animal = new Shark();
        第二次调用方法 : Animal animal = new Dog();
        第三次调用方法 : Animal animal = new Cat();
     */
    public static void useAnimal(Animal animal){//Animal animal : 刀把上的接口
        animal.eat();//动态绑定

        if (animal instanceof Shark){
            Shark shark = (Shark) animal;
            System.out.println("shark.weight = " + shark.weight);
            shark.diving();
        }

        if (animal instanceof Dog){
            Dog dog = (Dog) animal;
            System.out.println("dog.name = " + dog.name);
            dog.swim();
        }
        //向下转型需要提前做安全判断
        //shark类的字节码对象 == Cat类的字节码对象
        if (animal.getClass() == Cat.class){//false
            Cat cat = (Cat) animal;
            System.out.println("cat.age = " + cat.age);
            cat.catchMouse();
        }
    }

    public static Animal getAnimal(){
        //Animal = new Dog();
        return new Dog();
    }

}


interface Animal{
    public abstract void eat();
}

class Shark implements Animal{

    int weight;

    @Override
    public void eat() {
        System.out.println("鲨鱼吃人~");
    }

    public void diving(){
        System.out.println("潜水~");
    }
}

class Dog implements Animal{

    String name;

    @Override
    public void eat() {
        System.out.println("狗吃骨头~");
    }

    public void swim(){
        System.out.println("狗刨~");
    }
}

class Cat implements Animal{

    int age;

    @Override
    public void eat() {
        System.out.println("猫吃罐头~");
    }

    public void catchMouse(){
        System.out.println("猫抓老鼠~");
    }
}